package com.example.boot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.service.UploadService;
import com.example.common.Result;
import com.example.common.enums.RedisFileConstant;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.CustomException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/files")
@Api(tags = "文件上传相关接口")
public class FileController {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 文件上传存储路径
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Value("${server.port:9090}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        if(file != null) {
            System.out.println(file.getOriginalFilename());
            String url = uploadService.upload(file);
            if (StringUtils.hasLength(url)) {
                //上传的图片数据信息 Set类型；无序不重复 差集
                redisTemplate.opsForSet().add(RedisFileConstant.upload_file, url);
            }
            if (!StringUtils.hasLength(url)) {
                throw new CustomException(ResultCodeEnum.PARAM_ERROR);
            }
            return Result.success(url);
        }

        return Result.error(ResultCodeEnum.FILE_EMPTY_ERROR);
    }


    /**
     * 获取文件
     *
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")   //  1697438073596-avatar.png
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;
        try {
            if (StrUtil.isNotEmpty(flag)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + flag);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    /**
     * 删除文件
     *
     * @param flag
     */
    @DeleteMapping("/{flag}")
    public void delFile(@PathVariable String flag) {
        FileUtil.del(filePath + flag);
        System.out.println("删除文件" + flag + "成功");
    }
}
